﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

using EHTSaleManager.Code.BLL;
using EHTSaleManager.Code.Entity;
using EHTSaleManager.Code.Utility;

using Aspose.Cells;

namespace EHTSaleManager.UIAdmin
{
    public partial class AdminProducts : System.Web.UI.Page
    {
        private Int32 categoryID = -1;
        private Int32 pageIndex = 1;
        private Int32 pageSize = 10;
        private Int32 totalRecord;
        private Cells _range;
        private Worksheet _exSheet;

        private DataTable dtCategorys = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                categoryID = Int32.Parse(Request.QueryString["CategoryID"].ToString());
            }
            catch (Exception ex)
            {
                categoryID = -1;
            }

            try
            {
                pageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
               
            }
            catch (Exception)
            {
                pageIndex = 1;
            }
           
            if (!Page.IsPostBack)
            {
                //Fill data Category vào ddl
                dtCategorys = CategoryProvider.GetCategorysForBackEnd().Tables[0];
                CreateDDLCategory(0, 0);
                this.ddlCategory.Items.Insert(0, new ListItem("--- ALL Product ---", "-1"));
                this.ddlCategory.SelectedValue = categoryID.ToString();

                //load dữ liệu product
                LoadProductsByCategoryID(categoryID);
            }
        }


        /// <summary>
        /// Author : toanvt
        /// CreatedDate : 01/02/2012
        /// Description : tạo DropDownList bằng đệ quy
        /// </summary>
        /// <param name="parentID"></param>
        private void CreateDDLCategory(Int32 parentID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtCategorys.Select("ParentID = " + parentID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["CategoryID"].ToString());

                ListItem li = new ListItem(preString + drCategorysSub[i]["CategoryName"].ToString(), drCategorysSub[i]["CategoryID"].ToString());
                this.ddlCategory.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }

        private void LoadProductsByCategoryID(Int32 categoryID)
        {
            pageSize = this.PaggingControl1.PageSize;
            if (categoryID != -1)
            {
                DataSet dsProduct = ProductProvider.GetProductsByCategoryID(categoryID, pageIndex, pageSize, out totalRecord);
                this.rpProducts.DataSource = dsProduct;
                this.rpProducts.DataBind();
            }
            else
            {
                DataSet dsProduct = ProductProvider.GetAllProduct(pageIndex, pageSize, out totalRecord);
                this.rpProducts.DataSource = dsProduct;
                this.rpProducts.DataBind();
            }
           
            this.PaggingControl1.PageIndex = pageIndex;
            this.PaggingControl1.TotalRecord = totalRecord;
            this.PaggingControl1.PageURL = "AdminProducts.aspx?CategoryID=" + categoryID.ToString();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UIAdmin/AdminProduct.aspx?CategoryID=" + Int32.Parse(this.ddlCategory.SelectedValue.ToString()));
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("~/UIAdmin/AdminProducts.aspx?CategoryID=" + this.ddlCategory.SelectedValue);
            LoadProductsByCategoryID(Int32.Parse(this.ddlCategory.SelectedValue.ToString()));
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            
            int categoryID = Int32.Parse(this.ddlCategory.SelectedValue.ToString());
               // chuẩn bị tệp ghi dữ liêu
                string excelFile = Server.MapPath("~/ExcelTem/ListProduct.xls");
                Workbook exBook = new Workbook();
                exBook.Open(excelFile, FileFormatType.Excel2003);
                _exSheet = exBook.Worksheets[0];
                _range = _exSheet.Cells;
              // Ghi du lieu vao file excel
                int i = 5;
                DataSet dsProduct = ProductProvider.GetAllProductByCategoryID(categoryID);
                FillData("LIST PRODUCT", 2, 2);
                
                for (int j = 0; j < dsProduct.Tables[0].Rows.Count-1; j++)
                {
                    FillData(dsProduct.Tables[0].Rows[j]["CategoryID"], i, 1);
                    FillData(dsProduct.Tables[0].Rows[j]["CategoryName"], i, 2);
                    FillData(dsProduct.Tables[0].Rows[j]["ProductID"], i, 3);
                    FillData(dsProduct.Tables[0].Rows[j]["ProductName"], i, 4);
                    FillData(dsProduct.Tables[0].Rows[j]["QuantityPerUnit"], i, 5);
                    FillData(dsProduct.Tables[0].Rows[j]["Price"], i, 6);
                    FillData(dsProduct.Tables[0].Rows[j]["PricePerUnit"], i, 7);
                    FillData(dsProduct.Tables[0].Rows[j]["UnitsInStock"], i, 8);
                    FillData(dsProduct.Tables[0].Rows[j]["Discount"], i, 9);                   
                    i++;
                }
                exBook.Save("ListProduct.xls", SaveType.OpenInExcel, FileFormatType.Default, this.Response);
           
        }

        // ham fill du lieu vao excel
        protected void FillData(object value, int row, int column)
        {
            try
            {
                _exSheet.Cells[row - 1, column - 1].PutValue(value);
            }
            catch (Exception e)
            {

            }
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            Response.Redirect("AdminProductImportData.aspx");
        }
    }
}